package com.tanhua.server.service;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.mongo.Movement;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;


@Service
public class MovementService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    public void publishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        //判断发布动态的内容是否存在
        String textContent = movement.getTextContent();
        Long userId = UserHolder.getUserId();
        if (textContent == null){
            throw new BusinessException(ErrorResult.contentError());
        }
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String urls = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(urls);
        }
        movement.setUserId(userId);
        movement.setMedias(medias);
        movementApi.saveMovement(movement);
    }

    /**
     * 查询我的动态列表
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult myMovements(Long userId, Integer page, Integer pagesize) {
        PageResult pr = movementApi.findMyMovements(userId,page,pagesize);
        //取出分页对象中的动态数据
        List<Movement> items = (List<Movement>) pr.getItems();
        if (items == null){
            return pr;
        }
        //根据id查询用户详细数据
        UserInfo userInfo = userInfoApi.getById(userId);

        //遍历动态数据,为每一条动态数据添加发布者的详细信息
        ArrayList<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            MovementsVo vo = new MovementsVo();
            vo = vo.init(userInfo, item);
            list.add(vo);
        }
        pr.setItems(list);
        return pr;
    }
}
